package fr.mehfile.api.connexion;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.util.Log;

public class HttpConnection {

	private static final String TAG = "HttpConnection";

	private DefaultHttpClient client = null;

	private Header[] headers = null;

	private HttpParams httpParams = new BasicHttpParams();

	public HttpConnection() {
		httpParams = new BasicHttpParams();
		client = new DefaultHttpClient(httpParams);
	}

	public Header[] getHeaders() {
		return headers;
	}

	public void setHeaders(Header[] headers) {
		this.headers = headers;
	}

	public int getConnectionTimeOut() {
		return HttpConnectionParams.getConnectionTimeout(httpParams);
	}

	public void setConnectionTimeOut(int connectionTimeOut) {
		HttpConnectionParams
				.setConnectionTimeout(httpParams, connectionTimeOut);
	}

	public int getSocketTimeOut() {
		return HttpConnectionParams.getSoTimeout(httpParams);
	}

	public void setSocketTimeOut(int socketTimeOut) {
		HttpConnectionParams.setSoTimeout(httpParams, socketTimeOut);
	}

	public InputStream doGetRequest(URI adresse) throws Exception {

		HttpGet request = new HttpGet(adresse);

		if (headers != null)
			request.setHeaders(headers);

		HttpResponse response = client.execute(request);

		HttpEntity entity = response.getEntity();
		if (entity == null)
			throw new Exception();

		if (response.getStatusLine().getStatusCode() != 200) {
			throw new HttpConnectionException(response.getStatusLine()
					.getStatusCode());
		}

		return entity.getContent();
	}

	/**
	 * Issue a POST request to the server.
	 * 
	 * @param endpoint
	 *            POST address.
	 * @param params
	 *            request parameters.
	 * 
	 * @throws IOException
	 *             propagated from POST.
	 */
	public static void post(String endpoint, Map<String, String> params)
			throws IOException {
		URL url;
		try {
			url = new URL(endpoint);
		} catch (MalformedURLException e) {
			throw new IllegalArgumentException("invalid url: " + endpoint);
		}
		StringBuilder bodyBuilder = new StringBuilder();
		Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
		// constructs the POST body using the parameters
		while (iterator.hasNext()) {
			Entry<String, String> param = iterator.next();
			bodyBuilder.append(param.getKey()).append('=')
					.append(param.getValue());
			if (iterator.hasNext()) {
				bodyBuilder.append('&');
			}
		}
		String body = bodyBuilder.toString();
		Log.v(TAG, "Posting '" + body + "' to " + url);
		byte[] bytes = body.getBytes();
		HttpURLConnection conn = null;
		try {
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setFixedLengthStreamingMode(bytes.length);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded;charset=UTF-8");
			// post the request
			OutputStream out = conn.getOutputStream();
			out.write(bytes);
			out.close();
			// handle the response
			int status = conn.getResponseCode();
			if (status != 200) {
				throw new IOException("Post failed with error code " + status);
			}
		} finally {
			if (conn != null) {
				conn.disconnect();
			}
		}
	}

}
